package puzzle.projecteuler.p100;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import astudy.util.Permutation;

public class Problem079B {

	/**
	 * 测试数据中只包含0,1,2,3,6,7,8,9,没有4,5。
	 * 所以至少字符串长度是8。
	 * 遍历所有可能试一下，得到唯一解“73162890”
	 * 
	 * 
	 * 对于一般问题，应该有好的算法实现。暂时我还不了解。
	 * 
	 * 
	 * @param args
	 */
	public static void main(String[] args) throws IOException {
		
		String[] ds = readData();
		int[] c = new int[] {0,1,2,3,6,7,8,9};
		while (c != null) {
			if (check(c, ds)) {
				print(c);
			}
			c = Permutation.next(c);
		}
	}
	
	private static boolean check(int[] c, String[] ds) {
		for (String d: ds) {
			if (!check(c, d)) return false;
		}
		return true;
	}

	private static boolean check(int[] c, String d) {
		String s = "";
		for (int j = 0; j < c.length; j ++) {
			if (d.indexOf(""+c[j]) > -1) {
				s += c[j];
			}
		}
		return d.equalsIgnoreCase(s);
	}

	private static void print(int[] c) {
		for (int j = 0; j < c.length; j ++) {
			System.out.print(c[j]);
		}
		System.out.println();
	}
	
	public static String[] readData() throws IOException {

		URL url = Problem079B.class.getResource("Problem079.txt");
		File file = new File(URLDecoder.decode(url.getPath(), "UTF-8"));

		BufferedReader br = new BufferedReader(new FileReader(file));
		String line = null;
		Set<String> tmp = new HashSet<String>();
		while ((line = br.readLine()) != null) {
			tmp.add(line);
		}
		br.close();
		String[] ds =  tmp.toArray(new String[tmp.size()]);
		Arrays.sort(ds);
		return ds;
	}
}
